<template>
  <div class="page-classifyList">
    <filter-view @update-list="() => getAtlasList()" />
    <a-table
      id="classifyDrag"
      :row-selection="{
      selectedRowKeys: statusState.selectedRowKeys,
      checkStrictly: false,
      getCheckboxProps: (record: AtlasListData) => {
        return { disabled: record.level === 1 && record?.subcateg?.length > 0 }
      },
      onChange: onSelectChange
    }"
      :rowClassName="(record:AtlasListData)=>{
       return record.level === 2 ? 'childBg' : ''
      }"
      :expandedRowKeys="openRowKeys"
      @expandedRowsChange="expandedRowsChangeFunc"
      :expandRowByClick="false"
      row-key="id"
      :columns="columns"
      :pagination="false"
      key="id"
      childrenColumnName="subcateg"
      :indentSize="0"
      :defaultExpandAllRows="true"
      :data-source="statusState.atlasList"
      :loading="state.loading"
      :scroll="{ x: 1500 }"
    >
      <template #headerCell="{ column }">
        <template v-if="column.key === 'name'">
          <span @click="handleOpenKeys">
            <plus-square-outlined v-if="!isOpen" />
            <minus-square-outlined v-else />
            {{ column.title }}
          </span>
        </template>
      </template>
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'sort'">
          <menu-outlined />
        </template>
        <template v-else-if="column.key === 'cover'">
          <a-image
            v-if="record.cover"
            width="37.82px"
            height="48px"
            :src="baseUrl + record.cover"
            :fallback="defaultImage"
          />
          <span v-else></span>
        </template>
        <template v-else-if="column.key === 'id'">
          <span>
            {{ record.id }}
          </span>
        </template>
        <template v-else-if="column.key === 'name'">
          <span v-if="!statusState.isEdit">
            <a-tooltip placement="top" color="#fff">
              <template #title>
                {{ record.name }}
              </template>
              <div class="ellipsis-text">{{ record.name }}</div>
            </a-tooltip>
          </span>
          <a-input v-else v-model:value="record.name" :maxlength="30" class="w-[170px]" placeholder="请输入分类" />
        </template>
        <template v-else-if="column.key === 'status'">
          <span>
            <a-switch
              v-model:checked="record.status"
              :checkedValue="1"
              :unCheckedValue="2"
              @change="(checked:any) => editStatus(checked, record)"
            />
          </span>
        </template>
        <template v-else-if="column.key === 'action'">
          <span>
            <a class="basicColor" @click="handleAddSubClass(record)" v-if="record.level === 1">
              添加子类
              <a-divider type="vertical" />
            </a>
            <a class="basicColor" @click="updateClass(record)"
              >编辑
              <a-divider type="vertical" />
            </a>
            <a class="basicColor" @click="deleteClass(record)" v-if="!isCheck(record)"> 删除 </a>
            <a v-else @click="() => message.error('删除失败，分类下有子类时不允许被删除')">删除</a>
          </span>
        </template>
      </template>
    </a-table>
    <!-- 删除对话框 -->
    <modal-view
      title="提示"
      v-model:visible="deleteVisible"
      okText="确定"
      cancelText="取消"
      :width="458"
      @confirm="deleteConfirm"
      @cancel="deleteCancel"
    >
      <span>{{ level === 1 ? '确定要删除该分类吗' : '确定要删除该子类吗' }}</span>
    </modal-view>
    <!-- 新建分类对话框 -->
    <modal-view
      :title="statusState.isAddClass ? '新建分类' : '编辑分类'"
      v-model:visible="statusState.addClassify"
      okText="确定"
      cancelText="取消"
      :width="511"
      :afterClose="afterCloseEdit"
      @confirm="addConfirm"
      @cancel="addCancel"
    >
      <a-form ref="formRef" :model="addFormState" :rules="addFormRules">
        <a-form-item label="分类名称" name="categ_name">
          <a-input
            v-model:value.trim="addFormState.categ_name"
            :maxlength="30"
            class="w-[359px]"
            placeholder="请输入分类名称"
          />
        </a-form-item>
        <a-form-item label="封面" name="categ_cover">
          <NormalUploadImageVue
            imgType="2"
            fileType="0"
            fileUrl="v1/common/upload"
            :imgSrc="addFormState.categ_cover"
            @getImageInfo="getImageInfo"
          />
        </a-form-item>
        <a-form-item label="序号" name="categ_order">
          <a-input-number
            v-model:value.trim="addFormState.categ_order"
            :min="0"
            :max="999999"
            placeholder="请输入序号"
            class="w-full"
          />
        </a-form-item>
        <a-form-item label="状态" name="categ_status">
          <a-radio-group v-model:value="addFormState.categ_status">
            <a-radio :value="1" class="mr-[80px]">启用</a-radio>
            <a-radio :value="2">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </modal-view>
    <!-- 添加子类对话框 -->
    <modal-view
      :title="statusState.isAddSubClass ? '添加子类' : '编辑子类'"
      v-model:visible="statusState.addSubClassify"
      okText="确定"
      cancelText="取消"
      :afterClose="afterCloseSubEdit"
      :width="511"
      @confirm="addSubConfirm"
      @cancel="addSubCancel"
    >
      <a-form ref="subFormRef" :model="addSubFormState" :rules="addSubFormRules">
        <a-form-item label="所属分类" name="categ_id">
          <a-select
            v-model:value="addSubFormState.categ_id"
            placeholder="请选择所属分类"
            :disabled="statusState.isAddSubClass ? false : true"
            class="w-[359px]"
            :getPopupContainer="(triggerNode: any) => triggerNode.parentNode"
          >
            <a-select-option :value="item.id" v-for="item in classFilterList" :key="item.id"
              >{{ item.name }}
            </a-select-option>
          </a-select>
        </a-form-item>
        <a-form-item label="子类名称" name="subcateg_name">
          <a-textarea
            v-model:value.trim="addSubFormState.subcateg_name"
            :maxlength="1000"
            placeholder="请输入子类名称，批量添加多个子类使用逗号“,”分隔"
            :rows="5"
            style="maxwidth: 359px !important"
          />
        </a-form-item>
        <a-form-item label="序号" name="subcateg_order">
          <a-input-number
            v-model:value.trim="addSubFormState.subcateg_order"
            :min="0"
            :max="999999"
            placeholder="请输入序号"
            class="w-full"
          />
        </a-form-item>
        <a-form-item label=" 状态" name="subcateg_status">
          <a-radio-group v-model:value="addSubFormState.subcateg_status">
            <a-radio :value="1" class="mr-[80px]">启用</a-radio>
            <a-radio :value="2">禁用</a-radio>
          </a-radio-group>
        </a-form-item>
      </a-form>
    </modal-view>
  </div>
</template>
<script lang="ts" setup>
import { ref, onMounted, reactive, computed, watch, inject } from 'vue'
import { message } from 'ant-design-vue'
//import Sortable from 'sortablejs'
import FilterView from './components/FilterView.vue'
import { column } from './dataSource'
import type { AtlasListData } from '@/types/site/atlas/atlasClass'
import { statusState, atlasState } from './state'
import type { ICopyList } from './state'
import ModalView from '@/components/components/modal/ModalView.vue'
import NormalUploadImageVue from '@/components/components/normal-upload-image/NormalUploadImage.vue'
import apis from '@/apis'
import { storage } from '@/utils/storage'
import defaultImage from '@/assets/icon/defaultImage.png'
const {
  site: {
    atlas_classify_list,
    edit_status,
    atlas_filter_classify_list,
    atlas_add_classify,
    atlas_del_classify,
    atlas_update_classify,
    atlas_add_subClassify,
    atlas_update_subClassify
  }
} = apis
const columns = ref(column)
const deleteVisible = ref(false)
const formRef = ref()
const subFormRef = ref()
const baseUrl: any = inject('baseUrl')
type Key = string
interface IState {
  loading: boolean
  copyTableData: AtlasListData[]
}
const state = reactive<IState>({
  loading: false,
  copyTableData: []
})
interface IAddFormState {
  categ_name: string | undefined
  categ_cover: string | undefined
  categ_status: number
  site_id?: string | undefined
  categ_id?: string | undefined
  categ_order?: string
}
//新建分类
const addFormState = reactive<IAddFormState>({
  categ_name: '',
  categ_cover: '',
  categ_status: 1,
  categ_order: ''
})
const siteId = storage.get('siteId')

const classFilterList = ref<ICopyList[]>([])
const categ_id = ref('') //分类删除id
const level = ref() //区分你是父级还是子级
const openRowKeys = ref<string[]>([])
const isOpen = ref(false)
const noEmpty = /^[^ ]+$/
let validateCateName = (rule: any, value: any, callback: any) => {
  console.log('value: ', value)
  if (!value) {
    return Promise.reject('请输入分类名称')
  } else if (!noEmpty.test(value)) {
    return Promise.reject('分类名称不能包含空格')
  } else {
    return Promise.resolve()
  }
}
const isCheck = computed(() => (item: AtlasListData) => {
  const len = item?.subcateg?.length
  return item.level === 1 && len > 0
})
const addFormRules = reactive({
  categ_name: [{ required: true, validator: validateCateName, trigger: 'blur' }],
  categ_order: [{ required: true, message: '请输入序号' }]
})
interface ISubAddFormState {
  categ_id?: string | undefined
  subcateg_name: string | undefined
  subcateg_status: number
  subcateg_id?: string | undefined
  subcateg_order?: string
}

//添加子类
const addSubFormState = reactive<ISubAddFormState>({
  subcateg_id: undefined,
  subcateg_name: '',
  subcateg_status: 1,
  subcateg_order: ''
})
const addSubFormRules = reactive({
  categ_id: [{ required: true, message: '请选择所属分类' }],
  subcateg_name: [{ required: true, message: '请输入子类名称，批量添加多个子类使用逗号“,”分隔' }],
  subcateg_order: [{ required: true, message: '请输入序号' }]
})

//展开收齐所有行
const handleOpenKeys = () => {
  isOpen.value = !isOpen.value
  if (!isOpen.value) return (openRowKeys.value = [])
  openRowKeys.value = statusState.atlasList.map((item: any) => item.id)
}
const expandedRowsChangeFunc = (expandedRows: any) => {
  openRowKeys.value = expandedRows
}
//分类弹窗关闭事件
const afterCloseEdit = () => {
  formRef.value.resetFields()
}

//子分类弹窗关闭事件
const afterCloseSubEdit = () => {
  subFormRef.value.resetFields()
  atlasState.categ_id = undefined
}
//获取分类接口
const getAtlasList = () => {
  state.loading = true
  atlasState.site_id = siteId
  atlas_classify_list(atlasState)
    .then((res: any) => {
      statusState.atlasList =
        res?.categ.map((item: any) => {
          for (var key in item) {
            if (Array.isArray(item[key]) && item[key].length === 0) {
              delete item[key]
            }
          }
          return item
        }) ?? []
      console.log('分类列表: ', statusState.atlasList)
      // getCopyAtlasList()
      state.loading = false
    })
    .catch(() => {
      state.loading = false
    })
}
//获取筛选分类接口
const getCopyAtlasList = () => {
  atlas_filter_classify_list({ site_id: siteId }).then((res: any) => {
    classFilterList.value = res?.categ ?? []
  })
}
watch(
  () => statusState.addSubClassify,
  (val: boolean) => {
    if (!val) return false
    getCopyAtlasList()
  },
  { deep: true }
)
const onSelectChange = (rowKeys: Key[]) => {
  console.log('selectedRowKeys changed: ', rowKeys)
  statusState.selectedRowKeys = rowKeys
}
const deleteClass = (item: AtlasListData) => {
  console.log(item, '删除行数据')
  categ_id.value = item.id
  level.value = item.level
  deleteVisible.value = true
  statusState.isEdit = false
}
//添加子类
const handleAddSubClass = (item: any) => {
  console.log('item: ', item)
  statusState.addSubClassify = true
  statusState.isAddSubClass = true
  statusState.isEdit = false
  addSubFormState.categ_id = item.id
}
//编辑
const updateClass = (item: AtlasListData) => {
  statusState.isEdit = false
  console.log('item: ', item)
  if (item.level === 1) {
    statusState.addClassify = true
    statusState.isAddClass = false
    const { id, name, cover, status, order } = item
    addFormState.categ_id = id
    addFormState.categ_name = name
    addFormState.categ_cover = cover
    addFormState.categ_status = status
    addFormState.categ_order = order
  } else {
    statusState.addSubClassify = true
    statusState.isAddSubClass = false
    const { id, categ_id, name, status, order } = item
    addSubFormState.categ_id = categ_id
    addSubFormState.subcateg_id = id
    addSubFormState.subcateg_name = name
    addSubFormState.subcateg_status = status
    addSubFormState.subcateg_order = order
  }
}
//状态修改
const editStatus = (checked: number, row: AtlasListData) => {
  if (!statusState.isEdit) {
    const data = {
      type: row.level === 1 ? 5 : 6,
      status: checked,
      id: [row.id]
    }
    console.log('data: ', data.id)
    edit_status(data).then(() => {
      message.success(checked === 1 ? '启用成功' : '禁用成功')
      getAtlasList()
    })
  } else {
    row.status = checked
  }
}
/**
  删除分类对话框事件
 */
const deleteConfirm = (value: any) => {
  console.log('value: ', value)
  atlas_del_classify({ categ_id: [categ_id.value] }).then(() => {
    deleteVisible.value = value
    message.success(level.value === 1 ? '分类删除成功' : '子类删除成功')
    getAtlasList()
  })
}
const deleteCancel = () => {
  deleteVisible.value = false
}
/**
  新建/编辑分类对话框事件
 */
const addConfirm = (value: any) => {
  formRef.value.validate().then(() => {
    console.log(addFormState)
    if (statusState.isAddClass) {
      addFormState.site_id = siteId
      console.log('addFormState: ', addFormState)
      atlas_add_classify(addFormState).then(() => {
        message.success('新增分类成功')
        statusState.addClassify = value
        getAtlasList()
      })
    } else {
      atlas_update_classify(addFormState).then(() => {
        message.success('编辑分类成功')
        statusState.addClassify = value
        getAtlasList()
      })
    }
  })
}
const addCancel = () => {
  statusState.addClassify = false
}
/**
  添加子类对话框事件
 */
const addSubConfirm = (value: any) => {
  subFormRef.value.validate().then(() => {
    console.log(addSubFormState)
    if (statusState.isAddSubClass) {
      atlas_add_subClassify(addSubFormState).then(() => {
        message.success('新增子类成功')
        statusState.addSubClassify = value
        getAtlasList()
      })
    } else {
      const { categ_id, ...params } = addSubFormState
      atlas_update_subClassify(params).then(() => {
        message.success('编辑子类成功')
        statusState.addSubClassify = value
        getAtlasList()
      })
    }
  })
}
const addSubCancel = () => {
  statusState.addSubClassify = false
}
const getImageInfo = (url: string) => {
  addFormState.categ_cover = url
}
const activeRows = ref([])
//初始化表格拖动
// const initSortable = () => {
//   const sortTable = document.querySelector('#classifyDrag  tbody') as HTMLElement
//   if (!sortTable) return
//   new Sortable(sortTable, {
//     handle: '.ant-table-row',
//     fallbackOnBody: true,
//     ghostClass: 'blue-background-class',
//     animation: 150,
//     sort: true,
//     // 拖拽移动的时候
//     onMove: function ({ dragged, related }) {},
//     // async
//     onEnd(item) {
//       console.log('item: ', item)
//       let table = Object.assign([], state.atlasList)
//       let newTable: any = []
//       //将多维数组展开为一维数组
//       table.forEach((item: any) => {
//         // 如果有子类，将子类也push进去
//         if (item.children && item.children.length > 0) {
//           newTable.push(item)
//           item.children.forEach((i: any) => {
//             i.parentId = item.id
//             newTable.push(i)
//           })
//         } else {
//           newTable.push(item)
//         }
//       })
//       console.log('table: ', table)
//       const sourceObj = newTable[item.oldIndex as number]
//       console.log('sourceObj: ', sourceObj)
//       const targetObj = newTable[item.newIndex as number]
//       console.log('targetObj: ', targetObj)
//       // 判断是否为一级
//       if (!sourceObj.parentId && !targetObj.parentId) {
//         debugger
//         // 操作数据为一级
//         const currRow = newTable.splice(item.oldIndex, 1)[0]
//         newTable.splice(item.newIndex, 0, currRow)
//         let endTable: any = []
//         newTable.forEach((item: any) => {
//           if (!item.parentId) {
//             endTable.push(item)
//           }
//         })
//         state.atlasList = endTable
//         console.log('state.atlasList: ', state.atlasList)
//         state.copyTableData = endTable
//       } else {
//         // 以下为其他不被允许的操作
//         let oneResult = !sourceObj.parentId && targetObj.parentId
//         let TwoResult = sourceObj.parentId && !targetObj.parentId
//         let ThreeResult = sourceObj.parentId && targetObj.parentId && sourceObj.parentId !== targetObj.parentId
//         if (oneResult || TwoResult || ThreeResult) {
//           state.atlasList = []
//           // 重新渲染表格
//           nextTick(() => {
//             getAtlasList()
//             message.warning('只能在同级之间进行拖拽排序')
//           })
//         }
//       }
//       // const newIndex = item.newIndex as any
//       // const oldIndex = item.oldIndex as any
//       // const source = state.classifyList[oldIndex] // 谁
//       // const destination = state.classifyList[newIndex] // 移动到哪儿
//       // // 拖动后同步至state
//       // state.classifyList[newIndex] = source
//       // state.classifyList[oldIndex] = destination
//       // console.log('source: ', source);
//       // console.log('destination: ', destination);
//       // message.success('排序完成')
//       // // 执行接口更新拖动后的接口
//       // const params = {
//       //   sourceId: source.id, //旧数据id
//       //   destinationId: destination.id, //目标数据id
//       // };
//       // try {
//       //   const res = await api.sort(params);
//       //   if (res.code === 0) {
//       //     message.success(`移动成功`);
//       //   } else {
//       //     message.error(`移动失败`);
//       //   }
//       // } catch (e) {
//       //   message.error(`移动失败`);
//       // } finally {
//       //   emit('updateList')
//       // }
//     }
//   })
// }
onMounted(() => {
  // getCopyAtlasList()
  getAtlasList()
  // initSortable()
})
</script>
<style lang="less" scoped>
@basicColor: #0083ff;

:deep(.childBg) {
  background-color: #fafafa;
}

// :deep(.ant-table-cell-fix-right) {
//   background: transparent;
// }

:deep(.ant-form-item-label) {
  width: 80px;
  text-align: right;
}

:deep(.ant-form-item-label > label::after) {
  content: '';
}

.page-classifyList {
  padding-top: 6px;
  box-sizing: border-box;

  :deep(.ant-table-thead > tr > th) {
    color: #262626;
    font-weight: 500;
  }

  :deep(
      .ant-table-thead
        > tr
        > th:not(:last-child):not(.ant-table-selection-column):not(.ant-table-row-expand-icon-cell):not(
          [colspan]
        )::before
    ) {
    width: 0;
  }

  .ant-table-row {
    cursor: pointer;
  }

  :deep(.ant-table-cell .ant-table-cell-with-append) {
    display: flex;
    align-items: center;
  }

  :deep(.ellipsis-text) {
    max-width: 154px !important;
    white-space: nowrap;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    cursor: pointer;
  }

  .basicColor {
    color: @basicColor;
  }
}
</style>
